﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.IO;
using CodeCarvings.Piczard.Web;
using CodeCarvings.Piczard;
using System.Xml.Linq;

namespace Framework.WebmasterTool
{
    public partial class WebLink : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                //CleanImageUploadTemp();
                CallImageUpload();
                LoadWeblink();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Weblink.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void CleanImageUploadTemp()
        {
            foreach (var file in Directory.GetFiles(Server.MapPath(ConfigPaths.Path_ImageUploadTemp_Folder_MapPath)))
            {
                File.Delete(file);
            }
        }

        public void CallImageUpload()
        {
            ImageUpload(siuWeblinkImage);
        }

        public void ImageUpload(SimpleImageUpload ctrImageUpload)
        {
            ctrImageUpload.ImageBackColorApplyMode = PictureTrimmerImageBackColorApplyMode.DoNotApply;
            ctrImageUpload.CropConstraint = new FreeCropConstraint();
            ctrImageUpload.PreviewFilter = new FixedResizeConstraint(200, 200, System.Drawing.Color.Black);
            ctrImageUpload.Text_BrowseButton = "Upload ảnh";
            ctrImageUpload.Text_CancelUploadButton = "Huỷ";
            ctrImageUpload.Text_EditButton = "Sửa ảnh";
            ctrImageUpload.Text_RemoveButton = "Xoá ảnh";
        }

        public void LoadWeblink()
        {
            XDocument xDocWeblink = XDocument.Load(Server.MapPath(ConfigPaths.Path_Weblink_Xml));
            var listXEWeblink = xDocWeblink.Descendants("weblink").Select(wl => new { ID = wl.Element("id").Value.Trim(), Name = wl.Element("name").Value.Trim(), Url = wl.Element("url").Value.Trim(), Index = wl.Element("index").Value }).ToList();
            grvWeblink.DataSource = listXEWeblink;
            grvWeblink.DataBind();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            XDocument xDocWeblink = XDocument.Load(Server.MapPath(ConfigPaths.Path_Weblink_Xml));
            if (btnSave.CommandName == "Insert")
            {
                XElement xEWeblinkMaxID = xDocWeblink.Descendants("weblink").OrderByDescending(wl => (int)wl.Element("id")).FirstOrDefault();
                int id;
                if (xEWeblinkMaxID == null)
                {
                    id = 0;
                }
                else
                {
                    id = int.Parse(xEWeblinkMaxID.Element("id").Value.Trim()) + 1;
                }
                if (siuWeblinkImage.HasImage)
                {
                    string fileNameImage = Globals.GetFileName(siuWeblinkImage.SourceImageClientFileName);
                    siuWeblinkImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageWeblink_Folder + fileNameImage);
                    xDocWeblink.Root.Add(new XElement("weblink",
                        new XElement("index", txtWeblinkIndex.Text.Trim()),
                        new XElement("name", txtWeblinkName.Text.Trim()),
                        new XElement("name_en", txtWeblinkName_en.Text.Trim()),
                        new XElement("url", txtWeblinkUrl.Text.Trim()),
                        new XElement("id", id.ToString()),
                        new XElement("image",
                            new XElement("src", fileNameImage),
                            new XElement("alt", txtWeblinkAlt.Text.Trim()))));
                }
                else
                {
                    xDocWeblink.Root.Add(new XElement("weblink",
                        new XElement("index", txtWeblinkIndex.Text.Trim()),
                        new XElement("name", txtWeblinkName.Text.Trim()),
                        new XElement("name_en", txtWeblinkName_en.Text.Trim()),
                        new XElement("url", txtWeblinkUrl.Text.Trim()),
                        new XElement("id", id.ToString()),
                        new XElement("image",
                            new XElement("src", string.Empty),
                            new XElement("alt", txtWeblinkAlt.Text.Trim()))));
                }
                xDocWeblink.Save(Server.MapPath(ConfigPaths.Path_Weblink_Xml));

                //create db log
                CreateDBLog(null, null, TypeAction.Insert, "Tạo weblink: " + txtWeblinkName.Text.Trim() + " - " + txtWeblinkUrl.Text.Trim(), "", "", "", "",
                        "", "", "", "");

                LoadWeblink();
                ClearWeblinkToInsert();
                lblMsg.Text = "Thêm weblink mới thành công";
                lblMsg.ForeColor = System.Drawing.Color.Blue;
            }
            else
            {
                int id = int.Parse(btnSave.CommandArgument.ToString());
                XElement xEWeblink = xDocWeblink.Descendants("weblink").Where(wl => wl.Element("id").Value == id.ToString()).FirstOrDefault();
                xEWeblink.Element("index").Value = txtWeblinkIndex.Text.Trim();
                string oldTitle = xEWeblink.Element("name").Value;
                xEWeblink.Element("name").Value = txtWeblinkName.Text.Trim();
                xEWeblink.Element("name_en").Value = txtWeblinkName_en.Text.Trim();
                xEWeblink.Element("url").Value = txtWeblinkUrl.Text.Trim();
                if (siuWeblinkImage.HasNewImage == true)
                {
                    Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageWeblink_Folder_MapPath + xEWeblink.Element("image").Element("src").Value.Trim()));
                    string fileNameImage = Globals.GetFileName(siuWeblinkImage.SourceImageClientFileName);
                    siuWeblinkImage.SaveProcessedImageToFileSystem(ConfigPaths.Path_ImageWeblink_Folder + fileNameImage);
                    xEWeblink.Element("image").Element("src").Value = fileNameImage;
                }
                else if (siuWeblinkImage.HasImage == false)
                {
                    Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageWeblink_Folder_MapPath + xEWeblink.Element("image").Element("src").Value.Trim()));
                    xEWeblink.Element("image").Element("src").Value = "";
                }
                xEWeblink.Element("image").Element("alt").Value = txtWeblinkAlt.Text.Trim();
                xDocWeblink.Save(Server.MapPath(ConfigPaths.Path_Weblink_Xml));

                //create db log
                CreateDBLog(null, null, TypeAction.Update, "Cập nhật weblink: " + oldTitle + " - " + txtWeblinkName.Text.Trim(), "", "", "", "",
                        "", "", "", "");

                LoadWeblink();
                ClearWeblinkToInsert();
                lblMsg.Text = "Sữa weblink thành công";
                lblMsg.ForeColor = System.Drawing.Color.Blue;
            }
            //clear outputcache
            HttpResponse.RemoveOutputCacheItem("/Default.aspx");
            HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
            HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
            HttpResponse.RemoveOutputCacheItem("/Products.aspx");
            HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
            HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
        }

        private void ClearWeblinkToInsert()
        {
            txtWeblinkIndex.Text = txtWeblinkName.Text = txtWeblinkName_en.Text = txtWeblinkUrl.Text = txtWeblinkAlt.Text = "";
            btnDelete.Visible = btnNew.Visible = false;
            btnSave.CommandName = "Insert";
            siuWeblinkImage.UnloadImage();
            //CleanImageUploadTemp();
        }

        protected void imbWeblinkEdit_Command(object sender, CommandEventArgs e)
        {
            lblMsg.Text = "";
            int id = int.Parse(e.CommandArgument.ToString());
            LoadWeblinkDetails(id);
        }

        public void LoadWeblinkDetails(int id)
        {
            XDocument xDocWeblink = XDocument.Load(Server.MapPath(ConfigPaths.Path_Weblink_Xml));
            XElement xEWeblink = xDocWeblink.Descendants("weblink").Where(wl => wl.Element("id").Value == id.ToString()).FirstOrDefault();
            txtWeblinkIndex.Text = xEWeblink.Element("index").Value.Trim();
            txtWeblinkName.Text = xEWeblink.Element("name").Value.Trim();
            txtWeblinkName_en.Text = xEWeblink.Element("name_en").Value.Trim();
            txtWeblinkUrl.Text = xEWeblink.Element("url").Value.Trim();
            if (xEWeblink.Element("image").Element("src").Value.Trim() != "")
            {
                string srcImageWeblink = ConfigPaths.Path_ImageWeblink_Folder_MapPath + xEWeblink.Element("image").Element("src").Value.Trim();
                siuWeblinkImage.LoadImageFromFileSystem(Server.MapPath(srcImageWeblink));
            }
            else
            {
                siuWeblinkImage.UnloadImage();
            }
            txtWeblinkAlt.Text = xEWeblink.Element("image").Element("alt").Value.Trim();
            btnSave.CommandArgument = id.ToString();
            btnSave.CommandName = "Update";
            btnDelete.Visible = btnNew.Visible = true;
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            ClearWeblinkToInsert();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            XDocument xDocWeblink = XDocument.Load(Server.MapPath(ConfigPaths.Path_Weblink_Xml));
            int id = int.Parse(btnSave.CommandArgument.ToString());
            XElement xEWeblink = xDocWeblink.Descendants("weblink").Where(wl => wl.Element("id").Value.Trim() == id.ToString().Trim()).FirstOrDefault();
            Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageWeblink_Folder_MapPath + xEWeblink.Element("image").Element("src").Value));

            //create db log
            CreateDBLog(null, null, TypeAction.Delete, "Xoá weblink: " + xEWeblink.Element("name").Value + " - " + xEWeblink.Element("url").Value, "", "", "", "",
                "", "", "", "");

            xEWeblink.Remove();
            xDocWeblink.Save(Server.MapPath(ConfigPaths.Path_Weblink_Xml));
            LoadWeblink();
            ClearWeblinkToInsert();
            lblMsg.Text = "Xoá weblink thành công";
            lblMsg.ForeColor = System.Drawing.Color.Blue;
            //clear outputcache
            HttpResponse.RemoveOutputCacheItem("/Default.aspx");
            HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
            HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
            HttpResponse.RemoveOutputCacheItem("/Products.aspx");
            HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
            HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
        }

        protected void grvWeblink_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvWeblink.PageIndex = e.NewPageIndex;
            LoadWeblink();
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}